package com.nice.common.memory;

import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

public class BufferPoolTest {

    public void testCreateCompare() {
        int count = 5000000;
        BufferPool pool = BufferPool.getInstance();
        long st = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            ByteBuffer.allocate(128);
        }
        System.out.println(System.currentTimeMillis() - st);
        long st2 = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            pool.allocateBytebuf(128);
        }
        System.out.println(System.currentTimeMillis() - st2);
    }

    public static void testBufferpool() throws InterruptedException {
        int j = 50;
        Thread.sleep(5000);
        final BufferPool pool = BufferPool.getInstance();
        final CountDownLatch cd = new CountDownLatch(j);
        for (int i = 0; i < j; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    String string = Thread.currentThread().toString();
                    byte[] dst = new byte[string.length()];
                    byte[] bytes = string.getBytes();
                    try {
                        for (int i = 0; i < 1000000; i++) {
                             ByteBuffer buf = pool.allocateBytebuf(2048);
//                            ByteBuffer buf = ByteBuffer.allocate(1024);
                            buf.put(bytes);
                            buf.putInt(i);
                            buf.flip();
                            buf.get(dst);
                            // System.out.println(new String(dst));
                             pool.recovery(buf);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    cd.countDown();
                }
            }).start();
        }
        cd.await();
        System.out.println("unuse:" + pool.getAllocateTimes());
        System.out.println("use:" + pool.getRecoveryTimes());
        pool.clear();
        Thread.sleep(10000);
    }

    public static void main(String[] args) throws InterruptedException {
        testBufferpool();
    }
}
